
public class PacketReader
{
	//VARIABLES
	boolean handshake;
	String handshakeHeader;
	//zero bits byte[]
	int peerID;
	int messageLength;
	int messageType;
	byte[] data;
	int index;
	
	public PacketReader(byte[] input, boolean handshake)
	{
		this.data = input;
		this.handshake = handshake;
		if(this.handshake == true)
			processHandshake();
		else
			processMessage();
	}
	
	public PacketReader(byte[] index)
	{
		//get the Length
		String temp = "";
		for(int i=0; i<4; i++)
		{
			if(index[i] != 0)
			{ 
				temp = temp + (char)(index[i]);
			}
		}
		//convert the byte[] into an int
		this.index = Integer.parseInt(temp);
	}

	
	public PacketReader(byte[] index, byte[] file)
	{
		//get the Length
		String temp = "";
		for(int i=0; i<4; i++)
		{
			if(index[i] != 0)
			{ 
				temp = temp + (char)(index[i]);
			}
		}
		//convert the byte[] into an int
		this.index = Integer.parseInt(temp);
		
		this.data = file;
	}
	private void processHandshake()
	{
		//get the handshake header
		String temp = "";
		for(int i=0; i<18; i++)
		{
			if(data[i] != 0)
			{
				temp = temp + (char)(data[i]);
			}
		}
		//save handshake header
		this.handshakeHeader = temp;
		
		temp = "";
		for(int i=28; i<32; i++)
		{
			if(data[i] != 0)
			{ 
				temp = temp + (char)(data[i]);
			}
		}
		//convert the byte[] into an int
		this.peerID = Integer.parseInt(temp);
		
	}
	
	private void processMessage()
	{
		//get the Length
		this.messageLength = byteLengthToInt();
		
		//get the Type
		this.messageType = Integer.parseInt(Character.toString((char)(data[4])));
				
	}
	
	public int getPeerID()
	{
		if(this.handshake)
			return this.peerID;
		else
			return 0;
	}
	
	public int getMessageLength()
	{
		if(!this.handshake)
			return this.messageLength;
		else
			return 0;
	}
	
	public int getMessageType()
	{
		if(!this.handshake)
			return this.messageType;
		else
			return 0;
	}
	
	public int getIndex()
	{
		return this.index;
	}
	
	public byte[] getFile()
	{
		return this.data;
	}
	
	public int byteLengthToInt() {
        return (this.data[0] << 24)
                + ((this.data[1] & 0xFF) << 16)
                + ((this.data[2] & 0xFF) << 8)
                + (this.data[3] & 0xFF);
	}

}
